<?php
$controller_map = array(
    'books' => 'book',
);
try{
    require dirname(__FILE__) . '/../lib/auto_load.php';
    $request_method = $_SERVER['REQUEST_METHOD'];
    $uri = $_SERVER['REQUEST_URI']; //比如 /users/1
    $pos = strpos($uri,'?');
    if($pos !== false){
        $uri = substr($uri, 0, $pos);
    }
    function router($uri) {
        //首页
        if(0 < preg_match('/^\/$/', $uri)) {
                $c = new PermissionController();
                return $c->index();
        }
        //检查权限
        if(0 < preg_match('/^\/permission\/check$/', $uri)) {
                $c = new PermissionController();
                return $c->check();
        }
        //书列表
        if(0 < preg_match('/^\/books\/$/', $uri)) {
                $c = new BookController();
                return $c->index();
        }

        //添加一本书
        if(0 < preg_match('/^\/books\/add$/', $uri)) {
                $c = new BookController();
                return $c->add();
        }

        //添加一本书submit
        if(0 < preg_match('/^\/books\/add_submit$/', $uri)) {
            $c = new BookController();
            return $c->addSubmit();
        }

        //在一本书中添加文章
        if(0 < preg_match('/^\/books\/\w+\/add$/', $uri)) {
            $c = new ArticleController();
            return $c->add();
        }

        //在一本书中添加文章submit
        if(0 < preg_match('/^\/books\/\w+\/add_submit$/', $uri)) {
            $tmp = explode('/', $uri);
            $c = new ArticleController();
            return $c->addSubmit($tmp[2]);
        }

        //读一本书中的文章
        if(0 < preg_match('/^\/books\/\w+$/', $uri)) {
            $tmp = explode('/', $uri);
            $c = new ArticleController();
            return $c->get($tmp[2]);
        }

        //修改一本书中的某一篇文章
        if(0 < preg_match('/^\/books\/\w+\/\d+\/edit$/', $uri)) {
            $tmp = explode('/', $uri);
            $c = new ArticleController();
            return $c->edit($tmp[2], $tmp[3]);
        }

        //修改一本书中的某一篇文章submit
        if(0 < preg_match('/^\/books\/\w+\/\d+\/edit_submit$/', $uri)) {
            $tmp = explode('/', $uri);
            $c = new ArticleController();
            return $c->editSubmit($tmp[2], $tmp[3]);
        }

        $error = array(
            'code' => '404',
            'msg' => '查无此页',
        );
        throw new ControllerExceptionLib(json_encode($error));
    }
    $r = router($uri);
    BaseController::output($r);
}catch(ControllerExceptionLib $e){
    exit;
    //BaseController::output($data, $content_type);
}
exit;
?>
